/**
* @program: src
*
* @description:
*
* @author: Mr.chen
*
* @create: 2020-11-02 17:10
**/
package models
import (
	mydb "ydd-im/service/dbproxy/util/mysql/conn"
	"errors"
	"fmt"
	"ydd-im/config"
	//"fmt"
	"database/sql"
)

type Signconfigure struct {
	Id   		   int  `db:"id"`
	AppKey         string `db:"appkey"`
	AppSecret      string `db:"appsecret"`
	CreateTime     int `db:"createtime"` //创建时间
	ModifyTime     int `db:"modifytime"`
	State          int `db:"state"`
	SecretType     string `db:"secrettype"`
}

//orm 回调
func (s *Signconfigure) TableName() string {
	return TNSignconfigure()
}

func NewSignconfigure() *Signconfigure {
	return &Signconfigure{}
}

func (s *Signconfigure) GetSignconfigureInfo(appkey string,secrettype string) (signconfigure Signconfigure, err error) {
	sqlStr := "select id,appkey,appsecret from "+s.TableName()+" where appkey=? and secrettype =?"
	signconfigure = Signconfigure{}
	dbconn,err := mydb.DBConn("r")
	if err != nil {
		return signconfigure, err
	}
	err =  dbconn.Get(&signconfigure, sqlStr,appkey,secrettype)
	if err == sql.ErrNoRows { // 为空
		return signconfigure,nil
	}
	if err != nil {
		return signconfigure,err
	}
	return signconfigure,nil
}
func (s *Signconfigure) GetSystemId(appkey string,systemId string) (string,error){
	if len(appkey) > 0 { // 启用的是公有用户的
		IsPublicSign :=config.GetApiConfig().ApiBase.IsPublicSign
		if !IsPublicSign { // 查询相关的数据库，存在选用对应的秘钥

			signconfigureInfo,err :=s.GetSignconfigureInfo(appkey,"md5")
			if err != nil {
				return  "",errors.New("appkey查询出错")
			}
			if signconfigureInfo.Id ==0 { // 不存在的选用测试的
				systemId = fmt.Sprintf("%s_%s",config.AppName,systemId)
			}else{ // 使用私发的appkey
				systemId = fmt.Sprintf("%s_%s",signconfigureInfo.AppKey,systemId)
			}
		}else {
			systemId = fmt.Sprintf("%s_%s",config.AppName,systemId)
		}
	}else{
		systemId = fmt.Sprintf("%s_%s",config.AppName,systemId)
	}
	return  systemId,nil
}


